package com.common.util;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfStamper;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;

/**
 *将文件通过base64转换为字符串以方便使用json传输
 */
public class FileEncodeUtil {
    private static String ROOTDIR= "/u01/Server/imgbase" +File.separator;

    public static String encode(byte[] bytes){
        byte[] encodeBase64 = Base64.encodeBase64(bytes);
        return new String(encodeBase64);
    }

    public static byte[] decode(String str){
        return Base64.decodeBase64(str);
    }

    public static InputStream decodeToStream(String str){
        byte[] decode = decode(str);
        return new ByteArrayInputStream(decode);
    }
    public static void writePdf(String byteData, String fileName, HttpServletResponse response) throws IOException {
        byte[] bytes = FileEncodeUtil.decode(byteData);
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/pdf;charset=UTF-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + fileName + ".pdf");
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
        OutputStream out = response.getOutputStream();
        out.write(bytes);
        out.flush();
        out.close();
    }

    public static void insertImage(AcroFields form, PdfStamper stamper, String filedName, String fileSavePath) throws IOException, DocumentException, DocumentException, DocumentException {
        int pageNo = form.getFieldPositions(filedName).get(0).page;
        Rectangle signRect = form.getFieldPositions(filedName).get(0).position;
        float x = signRect.getLeft();
        float y = signRect.getBottom();

        fileSavePath = fileSavePath.replace("＼", File.separator);
        String dirName= ROOTDIR;
        String filePath = dirName + fileSavePath;

        File file = new File(filePath);

        BufferedImage bufferedImage = ImageIO.read(file);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", baos);
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        baos.close();

        Image image = Image.getInstance(imageInByte);
        // 获取操作的页面
        PdfContentByte under = stamper.getOverContent(pageNo);
        // 根据域的大小缩放图片
        image.scaleToFit(signRect.getWidth(), signRect.getHeight());
        // 添加图片
        image.setAbsolutePosition(x, y);
        under.addImage(image);
    }

}
